<?php


namespace app\blog\model;


use app\common\BaseModel;
use app\common\model\ArticleBaseModel;
use think\db\BaseQuery;
use think\Model;

class ArticleModel extends ArticleBaseModel
{
    /**
     * 获取文章
     * @param array $param
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function getArticleList(array $param)
    {
        // 根据参数的查询条件
        $article_title = $param['article_title'] ?? null;
        if($article_title!==null){
            $article_title = '%'.$param['article_title'].'%';
        }
        $condition = [
            'category_id' => ['article_category', '=', $param['category_id'] ?? null],
            'article_title' => ['article_title', 'like', $article_title],
        ];
        // 隐藏的字段
        $hidden = ['update_time', 'article_status'];
        // 额外的查询调解
        $extra = [
            ['article_status', '=', 1],
        ];
        // 排序
        $order = [
            'add_time' => 'desc'
        ];
        $with = ['articleCategory' => function (BaseQuery $query) {
            $query->visible(['id', 'category_name']);
        }, 'articleTag' => function (BaseQuery $query) {
            $query->visible(['id', 'tag_name', 'tag_color', 'icon_url']);
        }];
        return $this->withPaginate(
            $with, $param, $condition, $hidden, $extra, $order
        );
    }

    /**
     * 通过id查询文章
     * @param int|array $id
     * @return array|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getArticleById($id)
    {
        if(is_array($id)){
            return $this->with(['articleCategory' => function (BaseQuery $query) {
                $query->visible(['id', 'category_name']);
            }, 'articleTag' => function (BaseQuery $query) {
                $query->visible(['id', 'tag_name', 'tag_color', 'icon_url']);
            }])->whereIn('id', $id)
                ->where('article_status', '=', 1)
                ->select()
                ->toArray();
        }
        return $this->with(['articleCategory' => function (BaseQuery $query) {
            $query->visible(['id', 'category_name']);
        }, 'articleTag' => function (BaseQuery $query) {
            $query->visible(['id', 'tag_name', 'tag_color', 'icon_url']);
        }])
            ->where('article_status', '=', 1)
            ->find($id)
            ->toArray();
    }
}